package cn.wolfcode.wolf2w.service.impl;

import cn.wolfcode.wolf2w.domain.Destination;
import cn.wolfcode.wolf2w.domain.Region;
import cn.wolfcode.wolf2w.domain.Region;
import cn.wolfcode.wolf2w.excption.LogicExcption;
import cn.wolfcode.wolf2w.query.RegionQuery;
import cn.wolfcode.wolf2w.redis.service.IUserInfRedisService;
import cn.wolfcode.wolf2w.repository.RegionRepository;
import cn.wolfcode.wolf2w.service.IDestinationService;
import cn.wolfcode.wolf2w.service.IRegionService;
import cn.wolfcode.wolf2w.util.AssertUtil;
import cn.wolfcode.wolf2w.util.DBHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;

@Service
public class RegionServiceImpl implements IRegionService {

    @Autowired
    private RegionRepository repository;

    @Autowired
    private IDestinationService destinationService;

    @Autowired
    private MongoTemplate template;

    @Override
    public void save(Region region) {
        region.setId(null);
        repository.save(region);
    }

    @Override
    public void update(Region region) {
        repository.save(region);
    }

    @Override
    public void dilete(String id) {
        repository.deleteById(id);
    }

    @Override
    public Region get(String id) {
        return repository.findById(id).orElse(null);
    }

    @Override
    public List<Region> list() {
        return repository.findAll();
    }

    @Override
    public Page<Region> query(RegionQuery qo) {
        Query query = new Query();
        PageRequest pageable = PageRequest.of(qo.getCurrentPage() - 1, qo.getPageSize(), Sort.Direction.ASC, "_id");
        return DBHelper.query(template, query, qo, Region.class, pageable);
    }

    @Override
    public void saveOrUpdate(Region region) {
        if (!StringUtils.hasLength(region.getId())) {
            this.save(region);
        } else {
            this.update(region);
        }
    }

    @Override
    public void changeHotValue(int hot, String id) {
        Region region = this.get(id);
        region.setIshot(hot);
        this.update(region);
    }

    @Override
    public void deleteById(String id) {
        repository.deleteById(id);
    }



    @Override
    public List<Region> queryHotRegion() {
        return repository.findByIshotOrderBySequence(Region.STATE_HOT);
    }
}
